
/*
 * - xtabs contains several buttons/anchors/etc that can toggle div block that 
 *   has the similar id. One div is showing, the others are hiden. 
 */

(function( $ ){
	
	$.fn.xtabs = function(options) {
		
		var settings = $.extend({}, $.fn.xtabs.defaults, options);
		
		var tcPairs = $.parseJSON(settings.tabContentPairs);;
		var utPairs = $.parseJSON(settings.urlTabPairs);;
		
		this.each(function() {
			init(tcPairs, utPairs, settings);

			$(window).bind('popstate', function() {
				init(tcPairs, utPairs, settings);
			})
			
			$.each(tcPairs, function(t, c) {
				$("#" + t).bind({
					click: function(event) {
						selectContent(tcPairs, t);
						history.pushState({}, "page 2", $.xurls({
							operation: "set", 
							key: "t", 
							url: window.location.pathname, 
							value: getTitleByTab(utPairs, t)
							})
						);
					}
				});
			});
		});
		
	};
	
	function getTitleByTab(utPairs, tab) {
		for(u in utPairs) {
			if(utPairs[u] == tab) {
				jQuery.debug("meet " + u);
				return u;
			}
		}
	} 
	
	function init(tcPairs, utPairs, settings) {
		refresh(tcPairs, utPairs, settings);
	}
	
	function refresh(tcPairs, utPairs, settings) {
		var titleName = $.xurls({
			operation: "get", 
			key: "t", 
			url: window.location.pathname
			});
		if(titleName == "") {
			titleName = settings.defaultTitle;
		}
		jQuery.debug(titleName);
		jQuery.debug(utPairs[titleName]);
		selectContent(tcPairs, utPairs[titleName]);
	};
	
	function hideContent(id) {
		$("#" + id).hide();
	};
	
	function showContent(id) {
		//alert(id);
		$("#" + id).show();
	};
	
	function selectContent(tcPairs, id) {
		jQuery.debug("id is " + id);
		jQuery.debugo(tcPairs);
		$.each(tcPairs, function(i, n) {
			if(id != i) {
				jQuery.debug("hide this!: " + n);
				hideContent(n);
			}
			showContent(tcPairs[id]);
		});
		
	}; 
	
	$.fn.xtabs.defaults = {
		tabContentPairs		:	'{"tab1":"content1"}', 
		urlTabPairs			:	'{"title1":"tab1"}', 
		defaultTitle		:	'tab1'
	};
	
})( jQuery );